import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';

import { Tag, Select, Row, Col, Button, Form, Table, message } from 'antd';
import services from '../../../services/api';

import FormItem from '../../../components/FormItem';
import FilterTool from '../../../components/FilterTool';

function FromTemplate(props) {
  const [applications, setApplications] = useState([]);
  const [templates, setTemplates] = useState([]);
  const [events, setEvents] = useState([]);
  const [riskTypeList, setRiskTypeList] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);

  useEffect(() => {
    getApp(); // 获取渠道
    templatesList({}); // 获取渠道
  }, []);

  // 获取风险列表
  useEffect(() => {
    function getRiskTypeList() {
      services.policy.riskTypeList({}).then(res => {
        if (res.code === 0) {
          setRiskTypeList(res.data);
        }
      });
    }
    getRiskTypeList();
  }, []);

  // 过滤
  function refreshFilter(params) {
    templatesList(params);
  }

  // 获取策略模板
  function templatesList(params) {
    services.policy.templatesList(params).then(res => {
      if (res.code === 0) {
        setTemplates(res.data);
      }
    });
  }

  // 获取所属渠道
  function getApp() {
    services.application.getAppCodeList({}).then(res => {
      if (res.code === 0) {
        setApplications(res.data);
      }
    });
  }

  // 获取事件
  function getEvents(app_id) {
    services.event.getEventCodeList({ app_id }).then(res => {
      if (res.code === 0) {
        props.form.setFieldsValue({ event_id: '' });
        setEvents(res.data);
      }
    });
  }

  // 返回
  function back() {
    props.history.push('/strategy/config');
  }

  // 提交
  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        if (selectedRows.length === 0) {
          message.warning('请至少选择一条策略');
          return;
        }
        const params = {
          ...values,
          strategy_ids: selectedRows
        };

        services.policy.templatesCopy(params).then(res => {
          if (res.code === 0) {
            message.success('成功');
            props.history.push('/strategy/config');
          } else {
            message.error(res.msg);
          }
        });
      }
    });
  }

  function getColumns() {
    return [
      {
        title: '策略名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '风险类型',
        dataIndex: 'risk_type',
        key: 'risk_type',
        width: 400,
        render: text => {
          return (
            <>
              {text &&
                text.map(item => {
                  return <Tag key={item.name}>{item.name}</Tag>;
                })}
            </>
          );
        }
      },
      {
        title: '字段数量',
        dataIndex: 'field_ids',
        key: 'field_ids',
        render: text => {
          return <>{text && text.length}</>;
        }
      },
      {
        title: '描述',
        dataIndex: 'remark',
        key: 'remark'
      }
    ];
  }

  const layout = {
    labelCol: {
      span: 6
    },
    wrapperCol: {
      span: 18
    }
  };
  const { app_id, event_id } = {};
  const formItems = [
    {
      label: {
        label: '所属渠道',
        ...layout
      },
      name: 'app_id',
      options: {
        initialValue: app_id,
        rules: [{ required: true, message: '请选择渠道' }]
      },
      component: (
        <Select
          style={{ width: '100%' }}
          onChange={e => getEvents(e)}
          placeholder='请选择'
          disabled={props.actionType !== 'add'}
        >
          {applications
            .filter(it => it.app_id !== -1)
            .map(it => {
              return (
                <Select.Option value={it.app_id} key={it.app_id}>
                  {it.app_name}
                </Select.Option>
              );
            })}
        </Select>
      )
    },
    {
      label: {
        label: '关联事件',
        ...layout
      },
      name: 'event_id',
      options: {
        initialValue: event_id,
        rules: [{ required: true, message: '请选择关联事件' }]
      },
      component: (
        <Select style={{ width: '100%' }} placeholder='请选择' disabled={props.actionType !== 'add'}>
          {events
            .filter(it => it.event_id !== -1)
            .map(it => {
              return (
                <Select.Option value={it.event_id} key={it.event_id}>
                  {it.event_name}
                </Select.Option>
              );
            })}
        </Select>
      )
    }
  ];

  const rowSelection = {
    columnWidth: 30,
    onChange: (selectedRowKeys, selectedRows) => {
      const ids = selectedRows.map(item => item.strategy_id);
      setSelectedRows(ids);
    }
  };

  const data = [
    {
      type: 'Select',
      key: 'risk_type',
      name: 'risk_type',
      label: '按风险筛选',
      defaultValue: '',
      options: [
        ...riskTypeList.map(item => {
          return {
            value: item.code,
            name: item.name
          };
        })
      ],
      allowClear: true
    }
  ];

  return (
    <div className='from-template'>
      <div className='tantuer-field-area '>
        <div style={{ marginBottom: '10px' }}>
          系统已根据您可能遇到的风险，预置了多种策略，您可以按风险、策略两种维度进行浏览或引用。
        </div>
        <div className='form-title'>选择策略</div>
        <FilterTool
          data={data}
          colNum={3}
          refreshFilter={refreshFilter}
          isOnChange={true}
          isSearchNotSpaceBetween={true}
        />
        <Table columns={getColumns()} rowSelection={rowSelection} dataSource={templates} rowKey='strategy_id' />
      </div>
      <div className='tantuer-field-area tantuer-field-area-2'>
        <div className='form-title'>关联渠道与事件</div>
        <Form onSubmit={() => false} className='stretegy-wp-form'>
          <Row type='flex' gutter={20}>
            {formItems.map(item => {
              return (
                <Col span={12} key={item.name}>
                  <FormItem form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
          </Row>
          <Row type='flex' justify='start' className='form-submit-area'>
            <Col>
              <Button type='primary' onClick={handleSubmit}>
                确定
              </Button>
              <Button style={{ marginLeft: '15px' }} onClick={() => back()}>
                取消
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  );
}
function mapStateToProps(state) {
  return {
    codes: {
      ...state.code
    }
  };
}
export default connect(mapStateToProps)(Form.create()(FromTemplate));
